package edu.zerl.easyexceldemo.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import edu.zerl.easyexceldemo.entity.MonthReportDetailVO;
import edu.zerl.easyexceldemo.enums.ReadingStatusEnum;
import edu.zerl.easyexceldemo.enums.WxReceiveStatusEnum;
import edu.zerl.easyexceldemo.service.ExcelWriterService;
import edu.zerl.easyexceldemo.util.BaseExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

@Service
public class ExcelWriterServiceImpl implements ExcelWriterService {

    @Autowired
    BaseExportUtil baseExportUtil;

    @Override
    public void doDownLoad() {
        Consumer<ExcelWriter> consumer = writer -> {
            writer.write(generateMonthReport(), EasyExcel.writerSheet("月报信息")
                    .head(MonthReportDetailVO.class)
                    .build());
        };
        baseExportUtil.export("D:/月报信息.xlsx", consumer);
    }

    @Override
    public void webDownLoad() throws IOException {
        HttpServletResponse response =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

        List<MonthReportDetailVO> monthReportDetailVOList = generateMonthReport();

        this.setExcelRespProp(response, "月报信息");
        EasyExcel.write(response.getOutputStream())
                .head(MonthReportDetailVO.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("月报信息")
                .doWrite(monthReportDetailVOList);
    }

    /**
     * 设置excel下载响应头属性
     */
    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }

    private List<MonthReportDetailVO> generateMonthReport() {
        return Arrays.asList(new MonthReportDetailVO("客服小贝", 123123L, "182****1234", ReadingStatusEnum.NOT_READING, WxReceiveStatusEnum.ALREADY_RECEIVE),
                new MonthReportDetailVO("客服小贝2", 1231123L, "182****1235", ReadingStatusEnum.ALREADY_READING, WxReceiveStatusEnum.ALREADY_RECEIVE));
    }
}
